<?php
declare(strict_types=1);

namespace SixShop\Wechat\Service;

use EasyWeChat\MiniApp\Application;
use think\exception\InvalidArgumentException;
use think\facade\Cache;

class MiniApp extends Application
{
    public function __construct(string $appID = null)
    {
        $rawConfig = extension_config('wechat');
        if (!isset($rawConfig['app_id'], $rawConfig['secret'])) {
            throw new InvalidArgumentException('请先配置微信小程序信息, 插件管理中配置扩展信息app_id和secret');
        }
        $config = [
            'app_id' => $rawConfig['app_id'],
            'secret' => $rawConfig['secret'],
        ];
        if ($appID && $appID != $config['app_id']) {
            foreach ($rawConfig['extend'] as $item) {
                if ($item['app_id'] == $appID) {
                    $config = [
                        'app_id' => $item['app_id'],
                        'secret' => $item['secret'],
                    ];
                    break;
                }
            }
        }
        $config['use_stable_access_token'] = true;
        parent::__construct($config);
        $this->setCache(Cache::instance());
    }
}